package org.cjlm.ui.pub;

import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableModel;
import java.awt.*;

public class MTable extends JTable {
    private Color selectionBgColor = new Color(62, 142, 222); // 科技蓝
    private Color selectionFgColor = Color.WHITE;
    public MTable(TableModel dm) {
        super(dm);
        initUI();
    }

    private void initUI() {
        // 2. 全局表格线设置（确保行列分隔线可见）
        setShowGrid(true);
        setGridColor(new Color(189, 203, 215)); // 深灰色网格线
        setIntercellSpacing(new  Dimension(1, 1)); // 单元格间距

        // 3. 表头增强
        JTableHeader header = getTableHeader();
        header.setBackground(new  Color(70, 130, 180)); // 钢蓝色表头
        header.setForeground(Color.WHITE);
        header.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createMatteBorder(0,  0, 2, 0, Color.DARK_GRAY), // 底部粗线
                BorderFactory.createEmptyBorder(5,  5, 5, 5)
        ));

        // 新增交互增强
        setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); // 多行选择
        setRowMargin(2); // 行间距
        setRowHeight(28); // 统一行高

        setSelectionColors(new Color(189, 203, 215), Color.BLACK);
    }

    @Override
    public Component prepareRenderer(TableCellRenderer renderer, int row, int column) {
        Component comp = super.prepareRenderer(renderer,  row, column);

        // === 重构选中逻辑 ===
        Color defaultBg = Color.WHITE ;
        Color defaultFg = Color.BLACK;

        // 1. 行选中优先级最高（整行高亮）
        if (isRowSelected(row)) {
            comp.setBackground(selectionBgColor);
            comp.setForeground(selectionFgColor);
        }
        // 2. 单元格选中状态（局部高亮）
        else if (isCellSelected(row, column)) {
            comp.setBackground(selectionBgColor.darker());
            comp.setForeground(selectionFgColor);
        }
        // 3. 默认状态
        else {
            comp.setBackground(row  % 2 == 0 ? defaultBg : new Color(250, 250, 250));
            comp.setForeground(defaultFg);
        }

        // === 边框优化 ===
        if (comp instanceof JComponent) {
            Color borderColor = isRowSelected(row) ? selectionBgColor.darker()  : new Color(189, 203, 215);
            Border border = BorderFactory.createCompoundBorder(
                    BorderFactory.createMatteBorder(1,  0, 0, 1, borderColor),
                    BorderFactory.createEmptyBorder(2,  4, 2, 4)
            );
            ((JComponent) comp).setBorder(border);
        }

        return comp;
    }

    // 新增颜色设置方法
    public void setSelectionColors(Color bg, Color fg) {
        this.selectionBgColor  = bg;
        this.selectionFgColor  = fg;
    }
}
